from typing import List

class Solution:
    # O(n log n)
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        intervals = sorted(intervals, key=lambda x: x[0])
        res = []
        curr = []

        for interval in intervals:
            if len(curr) == 0:
                curr = [interval[0], interval[-1]]
            elif interval[0] <= curr[-1]:
                curr[-1] = max(curr[-1], interval[-1])
            else:
                res.append(curr[:])
                curr = [interval[0], interval[-1]]
        
        res.append(curr)
        return res
